package fragment;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import com.android.volley.VolleyError;
import com.easemob.EMCallBack;
import com.easemob.EMError;
import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMGroupManager;
import com.easemob.exceptions.EaseMobException;
import com.qzhy.female.R;
import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.bean.SHARE_MEDIA;

import Constant.Constance;
import Instance.LoginState;
import activity.CollecttActivity;
import activity.LoginActivity;
import activity.MamaActivity;
import activity.MineActivity;
import activity.MyMoneyActivity;
import activity.MyPostActivity;
import activity.SetActivity;
import activity.SignInActivity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import cn.jpush.android.api.TagAliasCallback;
import model.HxStatus;
import model.Sign_status;
import model.UserSign;
import utils.GsonUtils;
import utils.HTTPUtils;
import utils.MD5Utils;
import utils.SetUtils;
import volley.VolleyListener;

/**
 * A simple {@link Fragment} subclass.
 *
 */
public class MineFragment extends BaseFragment implements OnClickListener {
	private RelativeLayout mRtlRegist;
	private String UserType;
	private ImageView mImgUserIcon;
	private TextView mTvUsername;
	private RelativeLayout mRtlSet;
	private TextView mTvSign;
	private TextView mTvMoney;
	private TextView mTvMyPost;
	private TextView mTvCollect;
	private RelativeLayout mRtlMa;
	private UMShareAPI mShareAPI = null;//友盟分享
	public MineFragment() {
		
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View view =inflater.inflate(R.layout.fragment_mine, null);
		
		mShareAPI = UMShareAPI.get(getActivity());//友盟获取信息
		InitUI(view);
		InitUserState();
		return view;
	}

	private void InitUserState() {
		Log.e("用户的唯一Id", ""+SetUtils.GetUserId(getActivity()));
		Toast.makeText(getContext(), "用户Id:"+SetUtils.GetUserId(getActivity()), Toast.LENGTH_SHORT).show();
		if(LoginState.getInstance().isLogin(getContext())){
			mTvUsername.setText(SetUtils.GetUserName(getActivity()));
			utils.UILUtils.displayImage(SetUtils.GetUserIcon(getActivity()), mImgUserIcon);
		}	
		else {
			mTvUsername.setText("请登录");
			mImgUserIcon.setImageResource(R.drawable.ic_launcher);
		}
	}

	private void InitUI(View view) {
		mRtlRegist = (RelativeLayout) view.findViewById(R.id.rtl_regist);//未登录情况进入登陆界面
		mRtlRegist.setOnClickListener(this);
		
		mImgUserIcon = (ImageView) view.findViewById(R.id.img_usericon);
		mTvUsername = (TextView) view.findViewById(R.id.tv_username);
		
		mRtlSet = (RelativeLayout) view.findViewById(R.id.rtl_set);
		mRtlSet.setOnClickListener(this);
		
		mTvSign = (TextView) view.findViewById(R.id.tv_sign);
	    mTvSign.setOnClickListener(this);
	    
	    mTvMoney = (TextView) view.findViewById(R.id.tv_money);
	    mTvMoney.setOnClickListener(this);
	    mTvMyPost = (TextView) view.findViewById(R.id.tv_my_post);
	    mTvMyPost.setOnClickListener(this);
	    mTvCollect = (TextView) view.findViewById(R.id.tv_collect);
	    mTvCollect.setOnClickListener(this);
	    mRtlMa = (RelativeLayout) view.findViewById(R.id.rtl_ma);
	    mRtlMa.setOnClickListener(this);
	    
	    mTvInfo = (TextView) view.findViewById(R.id.tv_info);
	}
	

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.rtl_regist:
//			Intent intent = new Intent(getActivity(),LoginActivity.class);
//			startActivity(intent);
			boolean login = LoginState.getInstance().isLogin(getContext());
			if(login){
				Intent intent = new Intent(getActivity(),MineActivity.class);
				intent.putExtra(Constance.INTENT.USER_ID, SetUtils.GetUserId(getContext()));
				startActivityForResult(intent,Constance.INTENT.MIME_UPDATE_HEADER);
			}else {
				startActivityForResult(new Intent(getActivity(),LoginActivity.class),Constant.Constance.INTENT.LOGIN);
			}
			break;
		case R.id.rtl_set:	//设置
			startActivityForResult(new Intent(getActivity(), SetActivity.class),Constance.INTENT.SET_USERINFO);
			break;
		case R.id.tv_sign:
			SignIn();
			break;	
		case R.id.tv_money:
			LoginState.getInstance().startActivity(getActivity(), MyMoneyActivity.class);
			break;
		case R.id.tv_my_post:
			LoginState.getInstance().startActivity(getActivity(), MyPostActivity.class);
			break;
		case R.id.tv_collect:
			LoginState.getInstance().startActivity(getActivity(), CollecttActivity.class);
			break;
		case R.id.rtl_ma:	
			LoginState.getInstance().startActivity(getActivity(), MamaActivity.class);
			break;
		default:
			break;
		}
	}
	
	private void SignIn() {
		if(SetUtils.islogined(getContext())){
			startActivity(new Intent(getActivity(),SignInActivity.class));
		}else {
			startActivity(new Intent(getActivity(),LoginActivity.class));
		}
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if(data!=null){
			if(requestCode==Constant.Constance.INTENT.LOGIN){
				switch (resultCode) {
				
				case Constant.Constance.INTENT.lOGIN_XL:
					UserType=Constance.USERTYPE.XINLIANG;
					hxUser = MD5Utils.generate(SetUtils.getTime());
					SHARE_MEDIA platformXL = null;
					platformXL = SHARE_MEDIA.SINA;
					mShareAPI.getPlatformInfo(getActivity(), platformXL, umAuthListener);
					saveHxAccount();
					LoginJg();
					break;
				case Constance.INTENT.lOGIN_QQ:
					UserType=Constance.USERTYPE.QQ;
					hxUser = MD5Utils.generate(SetUtils.getTime());
					Log.i("Tiem", hxUser);
					SHARE_MEDIA platformQQ = null;
					platformQQ = SHARE_MEDIA.QQ;
					mShareAPI.getPlatformInfo(getActivity(), platformQQ, umAuthListener);
					saveHxAccount();
					break;
				case Constance.INTENT.lOGIN_WX:
					UserType=Constance.USERTYPE.WEIXIN;
					hxUser = MD5Utils.generate(SetUtils.getTime());
					SHARE_MEDIA platformWX = null;
					platformWX = SHARE_MEDIA.WEIXIN;
					mShareAPI.getPlatformInfo(getActivity(), platformWX, umAuthListener);
					break;
				case Constance.INTENT.LOGIN_NORMAL:	
					mTvUsername.setText(SetUtils.GetUserName(getActivity()));
					utils.UILUtils.displayImage(SetUtils.GetUserIcon(getActivity()), mImgUserIcon);
					saveHxAccount();
					break;
				default:
					break;
				}
			}
			if(requestCode==Constance.INTENT.SET_USERINFO){
				switch (resultCode) {
				case Constance.INTENT.LOGIN_SET:
					Toast.makeText(getActivity(), "退出登录", Toast.LENGTH_SHORT).show();
					InitUserState();
					break;
				case Constance.INTENT.SET_BACK:
					mTvUsername.setText(SetUtils.GetUserName(getActivity()));
					break;
				default:
					break;
				}
			}
			if(requestCode==Constance.INTENT.MIME_UPDATE_HEADER){
				switch (resultCode) {
				case Constance.INTENT.UPDATE_HEADER:
					 new Runnable() {
						public void run() {
							utils.UILUtils.displayImage(SetUtils.GetUserIcon(getActivity()), mImgUserIcon);
						}
					}.run();
					break;
				default:
					break;
				}
			}
	    }
	}
	/**
	 * 注册登录极光
	 */
	private void LoginJg() {
		
	}
	/**
	 * 注册到极光
	 */
	private void RegistJgUser() {
//		HTTPUtils.get(getContext(), Constance., listener);
	}

	/**
	 * 注册环信用户
	 */
	 protected void RegistHuanXinUser() {
		 new Thread(new Runnable() {
				public void run() {
					try {
						// 调用sdk注册方法
						EMChatManager.getInstance().createAccountOnServer(hxUser, "123");
						getActivity().runOnUiThread(new Runnable() {
							public void run() {
								Toast.makeText(getActivity(), "注册成功", 0).show();
							}
						});
					} catch (final EaseMobException e) {
						getActivity().runOnUiThread(new Runnable() {
							public void run() {
								int errorCode=e.getErrorCode();
								if(errorCode==EMError.NONETWORK_ERROR){
									Toast.makeText(getActivity(), "网络错误", Toast.LENGTH_SHORT).show();
								}else if(errorCode == EMError.USER_ALREADY_EXISTS){
									Toast.makeText(getActivity(), "用户已经存在", Toast.LENGTH_SHORT).show();
								}else if(errorCode == EMError.UNAUTHORIZED){
									Toast.makeText(getActivity(), "错误，没有权限", Toast.LENGTH_SHORT).show();
								}else if(errorCode == EMError.ILLEGAL_USER_NAME){
								    Toast.makeText(getActivity(), "非法的名字",Toast.LENGTH_SHORT).show();
								}else{
									Toast.makeText(getActivity(), "注册失败" + e.getMessage(), Toast.LENGTH_SHORT).show();
								}
							}
						});
					}
				}
			}).start();
	}

	private UMAuthListener umAuthListener = new UMAuthListener() {//登陆信息回掉
	        private String userId;
			private String UserName;
			private String UserImgUrl;
			private String UserGender;

			@Override
	        public void onComplete(SHARE_MEDIA platform, int action, final Map<String, String> data) {
	            if (data!=null){
	                Toast.makeText(getActivity(), data.toString(), Toast.LENGTH_SHORT).show();
	                switch (UserType) {
					case Constance.USERTYPE.QQ:
						UserGender = data.get("gender");
						UserName = data.get("screen_name");
						UserImgUrl = data.get("profile_image_url");
						userId = data.get("openid");
						break;
					case Constance.USERTYPE.XINLIANG:	
						UserGender = data.get("gender");
						UserName = data.get("screen_name");
						UserImgUrl = data.get("profile_image_url");
						userId = data.get("uid");
						break;
					case Constance.USERTYPE.WEIXIN:	
						UserGender = data.get("gender");
						UserName = data.get("screen_name");
						UserImgUrl = data.get("profile_image_url");
						userId = data.get("uid");
						break;
					default:
						break;
					}
	                getActivity().runOnUiThread(new Runnable() {
	                	@Override
	                	public void run() {
	                		mTvInfo.setText(data.toString());
	                		mTvUsername.setText(UserName);
							utils.UILUtils.displayImage(UserImgUrl, mImgUserIcon);
	                	}
	                });
	                SaveInfo();
	            }
	        }
			private void SaveInfo() {
	        	Map<String, String> params=new HashMap<String,String>();
	    		params.put("uid",""+userId);
	    		params.put("login_type", Constance.USERTYPE.QQ);
	    		params.put("nickname",UserName);
	    		params.put("profile_img",UserImgUrl);
	    		params.put("easemob_name", hxUser);
	    		params.put("jpush_id", hxUser);
	    		mTvInfo.setText("info:"+userId+UserName+hxUser);
	    		utils.HTTPUtils.post(getActivity(),Constance.URL.USER, params, new volley.VolleyListener() {
	    			@Override
	    			public void onResponse(String arg0) {
	    				Toast.makeText(getContext(), "信息获取成功"+arg0.toString(), Toast.LENGTH_LONG).show();
	    				Log.e("返回用户信息", arg0.toString());
	    				Sign_status sign = utils.GsonUtils.parseJSON(arg0, Sign_status.class);
	    				UserSign result = sign.getResult();
	    				if(sign.getStatus().equals(Constance.STATUS_TYPE.SUCCESS)){
	    					RegistHuanXinUser();
	    					RegistJgUser();
	    				}
	    				SetUtils.saveUserID(getActivity(), result.getId());
	    				SetUtils.saveUserName(getActivity(),result.getNickname());
	    				if(result.getProfileImg().startsWith("http")){
	    					SetUtils.saveUserIcon(getActivity(), result.getProfileImg());
	    				}else {
	    					SetUtils.saveUserIcon(getActivity(), Constance.URL.IMG_BASE+result.getProfileImg());
	    				}
	    			}
					
					@Override
	    			public void onErrorResponse(VolleyError arg0) {
	    				Toast.makeText(getContext(), "VolleyError"+arg0.toString(), Toast.LENGTH_LONG).show();
	    				Log.e("QQ返回用户信息", "返回失败");
	    			}
	    		});
	        }	

			@Override
	        public void onError(SHARE_MEDIA platform, int action, Throwable t) {
	            Toast.makeText( getActivity(), "get fail", Toast.LENGTH_SHORT).show();
	        }

	        @Override
	        public void onCancel(SHARE_MEDIA platform, int action) {
	            Toast.makeText( getActivity(), "get cancel", Toast.LENGTH_SHORT).show();
	        }
	    };
	private TextView mTvInfo;

	private String hxUser;
	private String myHxUser;
	
	public void saveHxAccount(){
		HTTPUtils.get(getActivity(), Constance.URL.USER+"/"+SetUtils.GetUserId(getContext())+"/easemob", new VolleyListener() {
			@Override
			public void onResponse(String arg0) {
				Log.i("获取环信账号", arg0.toString());
				Toast.makeText(getContext(), "获取环信账号"+arg0.toString(), 1).show();
				HxStatus hxStatus = GsonUtils.parseJSON(arg0, HxStatus.class);
				if(hxStatus.getStatus().equals(Constance.STATUS_TYPE.SUCCESS)){
					myHxUser= hxStatus.getResult().getEasemobName();
					String jpush_id = hxStatus.getResult().getJpush_id();
					Toast.makeText(getContext(), "极光Id"+SetUtils.GetJGId(getContext()), 1).show();
					LoginHx();
					utils.JgUtil.setAlias(getActivity(), jpush_id, new TagAliasCallback() {
						@Override
						public void gotResult(int arg0, String arg1, Set<String> arg2) {
						}
					});
				}
			}
			private void LoginHx() {
					EMChatManager.getInstance().login(myHxUser, "123", new EMCallBack() {
						@Override
						public void onSuccess() {
							getActivity().runOnUiThread(new Runnable() {
								@Override
								public void run() {
									try {
										EMGroupManager.getInstance().loadAllGroups();
										EMChatManager.getInstance().loadAllConversations();
										Toast.makeText(getContext(), "环信登陆成功:"+myHxUser, 1).show();
									} catch (Exception e) {
										e.printStackTrace();
									}
								}
							});
						}
						@Override
						public void onError(int i, final String s) {//此方法为子线程中的回调
							getActivity().runOnUiThread(new Runnable() {
								@Override
								public void run() {
								}
							});
						}
						@Override
						public void onProgress(int i, String s) {
						}
					});
			}
			@Override
			public void onErrorResponse(VolleyError arg0) {
			}
		});
	}
}
